package com.atguigu.edu.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.edu.realtime.app.BaseStreamApp;
import com.edu.realtime.common.Constant;
import com.edu.realtime.util.AtguiguUtil;
import com.edu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;
import java.util.Map;

public class DwdTrafficLog extends BaseStreamApp {
    private final String START = "start";
    private final String ACTION = "action";
    private final String DISPLAY = "display";
    private final String ERR = "err";
    private final String PAGE = "page";
    private final String APPVIDEO = "appVideo";

    public static void main(String[] args) {
        new DwdTrafficLog().init(3001,2,"DwdTrafficLog", Constant.TOPIC_ODS_LOG);
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //读取topic数据，做数据清洗
        SingleOutputStreamOperator<JSONObject> etledStream = etl(stream);
        //做新老客户纠正（如果 is_new 出错, 只会把老用户识别为新用户）
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etledStream);
        //分流：5个流
        Map<String, DataStream<JSONObject>> streams = splitStream(validatedStream);

       /* streams.get(PAGE).print(PAGE);
        streams.get(START).print(START);
        streams.get(ACTION).print(ACTION);
        streams.get(DISPLAY).print(DISPLAY);
        streams.get(ERR).print(ERR);*/
        //5个流分别写入到不同的topic中
        writeToKafka(streams);
    }

    private void writeToKafka(Map<String, DataStream<JSONObject>> streams) {
        streams.get(PAGE).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        streams.get(ERR).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        streams.get(DISPLAY).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        streams.get(ACTION).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        streams.get(START).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        streams.get(APPVIDEO).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_APPVIDEO));
    }

    private Map<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {
        /*
        * 获取侧流方法：
        * ①  OutputTag<JSONObject> displayTag = new OutputTag<>("display", TypeInformation.of(JSONObject.class));
        * ②  做成匿名内部类，否则侧输出流存的数据类型flink不知道
        *
        *       start action display page err
        *       start => 主流
        *       其他 => 侧流
        * */
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display"){};
        OutputTag<JSONObject> actionTag = new OutputTag<JSONObject>("action"){};
        OutputTag<JSONObject> errTag = new OutputTag<JSONObject>("err"){};
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {};
        OutputTag<JSONObject> appVideoTag = new OutputTag<JSONObject>("appVideo") {};

        SingleOutputStreamOperator<JSONObject> startStream = validatedStream.process(new ProcessFunction<JSONObject, JSONObject>() {
            @Override
            public void processElement(JSONObject obj, Context ctx, Collector<JSONObject> out) throws Exception {
                JSONObject common = obj.getJSONObject("common");
                JSONObject start = obj.getJSONObject("start");
                if (start != null) {
                    //start
                    out.collect(obj);
                } else {

                    //display
                    JSONArray displays = obj.getJSONArray("displays");
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            //把通用的一些字段放入到display中
                            display.putAll(common);
                            display.put("ts", obj.getLong("ts"));
                            ctx.output(displayTag, display);
                        }
                        //把曝光数据从obj中删除，为了不影响后面的侧流
                        obj.remove("displays");
                    }

                    //action
                    JSONArray actions = obj.getJSONArray("actions");
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);
                            action.putAll(common);
                            ctx.output(actionTag, action);
                        }
                        //把活动数据从obj中删除，为了不影响后面的侧流
                        obj.remove("actions");
                    }

                    //err
                    JSONObject err = obj.getJSONObject("err");
                    if (err != null) {
                        ctx.output(errTag, obj);
                        obj.remove("err");
                    }

                    //page
                    JSONObject page = obj.getJSONObject("page");
                    if (page != null) {
                        ctx.output(pageTag, obj);
                        obj.remove("page");
                    }

                    //page
                    JSONObject appVideo = obj.getJSONObject("appVideo");
                    if (appVideo != null) {
                        ctx.output(appVideoTag, obj);
                    }
                }
            }
        });
        //返回5个流
        DataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);
        DataStream<JSONObject> errStream = startStream.getSideOutput(errTag);
        DataStream<JSONObject> actionStream = startStream.getSideOutput(actionTag);
        DataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);
        DataStream<JSONObject> appVideoStream = startStream.getSideOutput(appVideoTag);

        Map<String, DataStream<JSONObject>> streams = new HashMap<>();
        streams.put(START,startStream);
        streams.put(ACTION,actionStream);
        streams.put(DISPLAY,displayStream);
        streams.put(ERR,errStream);
        streams.put(PAGE,pageStream);
        streams.put(APPVIDEO,appVideoStream);

        return streams;
    }

    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(SingleOutputStreamOperator<JSONObject> stream) {
        return stream
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, JSONObject>() {

                    private ValueState<String> firstVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        firstVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstVisitDate", String.class));
                    }

                    @Override
                    public JSONObject map(JSONObject obj) throws Exception {
                        String firstVisitDate = firstVisitDateState.value();

                        JSONObject common = obj.getJSONObject("common");
                        Long ts = obj.getLong("ts");
                        String today = AtguiguUtil.tsToDate(ts);
                        String isNew = common.getString("is_new");

                        /*
                        * 如果 is_new 出错, 只会把老用户识别为新用户
                        * 纠正：
                        *       keyBy: mid
                        *       is_new=1
                        *       搞一个状态: 存储这个用户的首次访问日期
                        *          首次: ①state=null 不用纠正  把今天存储到状态中
                        *               state != null today==fistDate 不用纠正
                        *               today != fistDate  需要纠正: 1=>0
                        * */
                        if ("1".equals(isNew)){
                            //首日首次
                            if (firstVisitDate == null) {
                                firstVisitDateState.update(today);
                            }else {
                                if (!today.equals(firstVisitDate)) {
                                   //今天不是首日，纠正is_new
                                    common.put("is_new","0");
                                }
                            }
                        }else {
                            //当程序启动之后，如果用户是老用户，则状态也是null，这个时候应该把状态设置为昨天
                            if (firstVisitDate == null){
                                String yesterday = AtguiguUtil.tsToDate(ts - 24 * 60 * 60 * 1000);
                                firstVisitDateState.update(yesterday);
                            }
                        }
                        return obj;
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream.filter((FilterFunction<String>) json -> {
            try {
                JSON.parseObject(json);
                return true;
            } catch (Exception e) {
                System.out.println("json格式数据不对：" + json);
                return false;
            }
        })
                .map(new MapFunction<String, JSONObject>() {
                    @Override
                    public JSONObject map(String json) throws Exception {
                        return JSON.parseObject(json);
                    }
                });
    }

}
